package com.hywood.live.pusher.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FetchUtils {
    private static final int CONNECTION_TIMEOUT = 10000;
    private static final String APP = "app";

    public static String getPusherUrl(String serviceUrl,String channelId,String channalPassword){
        return doHttpsRequest(serviceUrl + "verifyPrivilege/"+ APP +"/" + channelId + "?password=" + channalPassword, null,"GET");
    }
    public static String pauseLive(String serviceUrl,String guid){
        return doHttpsRequest(serviceUrl + "livepause/" + guid , null,"PUT");
    }
    public static String recoveryLive(String serviceUrl,String guid){
        return doHttpsRequest(serviceUrl + "liverecovery/" + guid , null,"PUT");
    }
    private static String doHttpsRequest(String serverURL, String body,String method) {

        try {
            URL url = new URL(serverURL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(method);
            urlConnection.setUseCaches(false);
            urlConnection.setDoInput(true);
//            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);



            if (body != null) {

                OutputStream os = null;
                os = new BufferedOutputStream(
                        urlConnection.getOutputStream());
                os.write(body.getBytes());
                os.flush();// writing your data which you post
            }

            urlConnection.connect();

            StringBuilder buffer = new StringBuilder();
            InputStream is = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(is));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            // reading your response

            is.close();
            urlConnection.disconnect();// close your connection
                return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
